package cn.vc.wallet.controller;

import cn.vc.auth.entity.po.VUser;
import cn.vc.wallet.entity.dto.WalletDto;
import cn.vc.wallet.service.WalletService;
import cn.vc.wallet.util.SecurityUtil;
import cn.vc.basicmodule.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/wallet")
public class WalletController {

    @Autowired
    private WalletService walletService;


    /**
     * 创建钱包
     * @param id 用户ID，同时作为钱包ID
     */
    @PostMapping()
    public void createWallet(@RequestParam("id") Long id) {
        walletService.createWallet(id);
    }
    /**
     * <h2>签到</h2>
     * @return cn.vc.basicmodule.entity.Result
     */
    @PostMapping("/signin")
    public Result<?> signIn() {
        VUser myUser = SecurityUtil.getUser();
        if (myUser==null) return Result.NOT_LOGGED_IN();
        // 签到
        Result<Integer> result = walletService.signIn(myUser.getId());
        return result;
    }


    /**
     * 投币接口
     */
    @DeleteMapping("/coincasting/{id}")
    public void coinCasting(@PathVariable("id") Long id) {
        walletService.updateCoin(id, -1);
    }


    /**
     * 查询用户钱包信息
     */
    @GetMapping
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<WalletDto> selectMyWallet() {
        VUser myUser = SecurityUtil.getUser();
        if (myUser==null) return Result.NOT_LOGGED_IN();
        return new Result<>(1, walletService.selectById(myUser.getId()));
    }


    /**
     * 钻石兑换金币
     */
    @PutMapping
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<Long> goldExchange(@RequestParam("diamond") Long diamond) {
        if (diamond==0) return new Result<>(1, 0L);
        VUser vUser = SecurityUtil.getUser();
        if (vUser==null) return Result.NOT_LOGGED_IN();

        Long coins = walletService.goldExchange(vUser.getId(), diamond);
        return new Result<>(1, coins);
    }

    /**
     * 扣除钻石
     */
    @PutMapping("/deduction")
    public boolean diamondDeduction(@RequestParam("id") Long id, @RequestParam("diamond") Long diamond) {
        return walletService.diamondDeduction(id, diamond);
    }

}
